package com.common.ibatis;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibatis.sqlmap.client.SqlMapClient;


public class IBatisUtil {
	private Logger log = LoggerFactory.getLogger(IBatisUtil.class);
	public int queryForCount(String sql,SqlMapClient sqlMapClient){
		Connection conn=null;
		Statement stm=null;
		int count=0;
		try {
			conn = sqlMapClient.getDataSource().getConnection();
			conn.setAutoCommit(true);
			stm = conn.createStatement();
			java.sql.ResultSet rs=stm.executeQuery(sql);
			while(rs.next()){
				count=rs.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("执行 sql ："+sql+"失败,异常信息:"+e);
		}finally{
			close(conn,stm);
		}
		return count;
	}
	
	private void close(Connection conn,Statement stm){
			try {
				if(stm!=null)
				stm.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.error("关闭stm 异常 "+e);
			}
			try {
				if(conn!=null)
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.error("关闭conn 异常 "+e);
			}
	}
}
